/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.controller.grant;

import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.util.TreeUtil;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.annotation.ControllerAuditLog;
import com.je.rbac.cache.FuncPermissionCache;
import com.je.rbac.exception.PermGroupException;
import com.je.rbac.service.grant.RbacGrantFuncPermissionService;
import com.je.rbac.service.grant.RbacGrantMenuPermissionService;
import com.je.rbac.service.grant.permgroup.RbacGrantPermGroupService;
import com.je.rbac.service.permission.GrantTypeEnum;
import com.je.rbac.service.permission.PermissionLoadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping(value = "/je/rbac/cloud/grant/permGroup")
public class RbacGrantPermGroupController extends AbstractPlatformController {

    @Autowired
    private RbacGrantMenuPermissionService rbacGrantMenuPermissionService;
    @Autowired
    private RbacGrantFuncPermissionService rbacGrantFuncPermissionService;
    @Autowired
    private RbacGrantPermGroupService rbacGrantPermGroupService;
    @Autowired
    private FuncPermissionCache funcPermissionCache;
    @Autowired
    private PermissionLoadService permissionLoadService;

    @RequestMapping(value = {"/loadPermGroups"}, method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "角色授权模块",operateTypeCode = "loadPermGroups",operateTypeName = "加载权限组树",logTypeCode = "securityManage",logTypeName = "安全管理")
    public BaseRespResult loadPermGroups(HttpServletRequest request) {
        String refresh = getStringParameter(request, "refresh");
        //清空缓存并重新加载
        if ("1".equals(refresh)) {
            funcPermissionCache.clear();
            permissionLoadService.reloadAllPermGroupPermCache(true);
        }

        List<DynaBean> permGroupList = metaService.select("JE_RBAC_PERMGROUP", ConditionsWrapper.builder().orderByAsc("SY_ORDERINDEX"));
        JSONTreeNode rootNode = TreeUtil.buildRootNode();
        rootNode.setExpanded(true);
        JSONTreeNode eachNode;
        for (DynaBean eachPermGroup : permGroupList) {
            eachNode = new JSONTreeNode();
            eachNode.setText(eachPermGroup.getStr("PERMGROUP_NAME"));
            eachNode.setCode(eachPermGroup.getStr("PERMGROUP_CODE"));
            eachNode.setChecked(false);
            eachNode.setIcon("fal fa-user-friends");
            eachNode.setNodeType("LEAF");
            eachNode.setLeaf(true);
            eachNode.setLayer("1");
            eachNode.setParent("ROOT");
            eachNode.setNodeInfoType("org");
            eachNode.setNodeInfo(eachPermGroup.getStr("PERMGROUP_CODE"));
            eachNode.setId(eachPermGroup.getStr("JE_RBAC_PERMGROUP_ID"));
            eachNode.setBean(eachPermGroup.getValues());
            eachNode.setExpanded(true);
            rootNode.getChildren().add(eachNode);
        }
        return BaseRespResult.successResult(rootNode);
    }

    @RequestMapping(value = {"/savePermGroup"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "角色授权模块",operateTypeCode = "savePermGroup",operateTypeName = "添加权限组",logTypeCode = "securityManage",logTypeName = "安全管理")
    public BaseRespResult savePermGroup(HttpServletRequest request) {
        String name = getStringParameter(request, "name");
        if (Strings.isNullOrEmpty(name)) {
            return BaseRespResult.errorResult("请指定名称！");
        }
        rbacGrantPermGroupService.insertPermGroup(name);
        return BaseRespResult.successResult("保存成功！");
    }

    @RequestMapping(value = {"/updatePermGroup"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "角色授权模块",operateTypeCode = "updatePermGroup",operateTypeName = "更新权限组",logTypeCode = "securityManage",logTypeName = "安全管理")
    public BaseRespResult updatePermGroup(HttpServletRequest request) {
        String id = getStringParameter(request, "id");
        String name = getStringParameter(request, "name");
        if (Strings.isNullOrEmpty(id)) {
            return BaseRespResult.errorResult("请选择要删除的权限组！");
        }
        if (Strings.isNullOrEmpty(name)) {
            return BaseRespResult.errorResult("请指定名称！");
        }
        try {
            rbacGrantPermGroupService.updatePermGroup(id, name);
        } catch (PermGroupException e) {
            return BaseRespResult.errorResult(e.getMessage());
        }
        return BaseRespResult.successResult("更新成功！");
    }

    @RequestMapping(value = {"/removePermGroup"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "角色授权模块",operateTypeCode = "removePermGroup",operateTypeName = "移除权限组",logTypeCode = "securityManage",logTypeName = "安全管理")
    public BaseRespResult removePermGroup(HttpServletRequest request) {
        String id = getStringParameter(request, "id");
        if (Strings.isNullOrEmpty(id)) {
            return BaseRespResult.errorResult("请选择要删除的权限组！");
        }
        try {
            rbacGrantPermGroupService.removePermGroup(id);
        } catch (PermGroupException e) {
            return BaseRespResult.errorResult(e.getMessage());
        }
        return BaseRespResult.successResult("删除成功！");
    }

    @RequestMapping(value = {"/moveGroup"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "角色授权模块",operateTypeCode = "movePermGroup",operateTypeName = "移动权限组",logTypeCode = "securityManage",logTypeName = "安全管理")
    public BaseRespResult moveGroup(HttpServletRequest request) {
        String id = getStringParameter(request, "id");
        String targetIndex = getStringParameter(request, "targetIndex");
        if (Strings.isNullOrEmpty(id)) {
            return BaseRespResult.errorResult("请选择要删除的权限组！");
        }
        if (Strings.isNullOrEmpty(targetIndex)) {
            return BaseRespResult.errorResult("请指定要挪到的目标位置！");
        }
        rbacGrantPermGroupService.move(id, Integer.valueOf(targetIndex));
        return BaseRespResult.successResult("移动成功！");
    }

    /**
     * 保存角色菜单授权
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/savePermGroupMenuPermission"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "角色授权模块",operateTypeCode = "savePermGroupMenuPermission",operateTypeName = "更新权限组菜单授权",logTypeCode = "securityManage",logTypeName = "安全管理")
    public BaseRespResult savePermGroupMenuPermission(HttpServletRequest request) {
        String permGroupIds = getStringParameter(request, "permGroupIds");
        String addedStrData = getStringParameter(request, "addedStrData");
        String deletedStrData = getStringParameter(request, "deletedStrData");
        if (Strings.isNullOrEmpty(addedStrData) && Strings.isNullOrEmpty(deletedStrData)) {
            return BaseRespResult.errorResult("无数据操作！");
        }
        //更新权限
        try {
            rbacGrantMenuPermissionService.updatePermGroupMenuPermissions(GrantTypeEnum.MENU, permGroupIds, addedStrData, deletedStrData);
        } catch (Throwable e) {
            e.printStackTrace();
            return BaseRespResult.errorResult(e.getMessage());
        }

        return BaseRespResult.successResult("保存授权成功！");
    }

    /**
     * 保存功能授权
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/savePermGroupFuncPermission"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "角色授权模块",operateTypeCode = "savePermGroupFuncPermission",operateTypeName = "更新权限组功能授权",logTypeCode = "securityManage",logTypeName = "安全管理")
    public BaseRespResult saveRoleFuncPermission(HttpServletRequest request) {
        String permGroupIds = getStringParameter(request, "permGroupIds");
        String addedStrData = getStringParameter(request, "addedStrData");
        String deletedStrData = getStringParameter(request, "deletedStrData");

        if (Strings.isNullOrEmpty(addedStrData) && Strings.isNullOrEmpty(deletedStrData)) {
            return BaseRespResult.errorResult("无数据操作！");
        }
        rbacGrantFuncPermissionService.updatePermGroupFuncPermissions(GrantTypeEnum.FUNC, permGroupIds, addedStrData, deletedStrData);
        return BaseRespResult.successResult("保存授权成功！");
    }

    /**
     * 保存APP授权
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/saveRoleAppPermission"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "角色授权模块",operateTypeCode = "savePermGroupAppPermission",operateTypeName = "更新权限组APP授权",logTypeCode = "securityManage",logTypeName = "安全管理")
    public BaseRespResult saveRoleAppPermission(HttpServletRequest request) {
        return BaseRespResult.errorResult("此版本不包括此功能！");
    }

}
